<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\Attendance\Integral;
use App\Http\Requests\Logic\Excellent\ExcellentListRequest;

class ExcellentController extends Controller
{
	public function list(ExcellentListRequest $request)
	{
		$project_id = $request->get('project_id');

		$string = date('Y-m', strtotime('-1 month'));
		$year = substr($string, 0, 4);
		$month = substr($string, 5, 2);

		/*查询出该项目所有用户*/
		$users = User::query()
			->where('project_id', $project_id)
			->selectRaw('users.name,users.id')
			->get();

		/*查询出上月分数*/
		$score = Integral::query()
			->whereYear('date', $year)
			->whereMonth('date', $month)
			->where('project_id', $project_id)
			->selectRaw('sum(score) as total,user_id')
			->groupBy('user_id')
			->get();

		$users->map(function ($item) use ($score) {
			$item->score = 0;
			foreach ($score as $key => $val) {
				if ($val->user_id == $item->id) {
					$item->score = (int)$val->total;
				}
			}
			return $item;
		});
		/*分数从高到低排序*/
		$list_excellent = $users->sortByDesc('score');
		/*取前面三个的值*/
		$list1 = $list_excellent->values()->take(3);

		/*分数从低到高排序*/
		$list_dis_excellent = $users->sortBy('score');
		/*取前面三个的值*/
		$list2 = $list_dis_excellent->values()->take(3);

		$data = [
			'excellent' => $list1,
			'dis_excellent' => $list2,
		];
		return success($data);
	}
}
